// 用于保存当前播放的状态
let currentSong = null;
let lastStartTime = 0;
let currentSongIndex = -1;
let playlist = [];
async function fetchCurrentSong() {
    try {
        const response = await fetch(contextPath + '/listenTogether.MusicControlServlet');
        const data = await response.json();

        const audioPlayer = document.getElementById("audioPlayer");
        const songTitle = document.getElementById("songTitle");

        // 检查服务器返回的歌曲是否与当前播放的不同
        if (data.song !== currentSong) {
            // 只有在歌曲变更时才更新播放
            currentSong = data.song;
            audioPlayer.src = "Music/" + currentSong;
            lastStartTime = data.startTime;
            const elapsedTime = (Date.now() - lastStartTime) / 1000;
            audioPlayer.currentTime = elapsedTime;
            audioPlayer.play();
            songTitle.innerText = currentSong;
        } else {
            // 计算当前时间偏差并只调整 currentTime
            songTitle.innerText = currentSong;
            const elapsedTime = (Date.now() - lastStartTime) / 1000;
            const timeDifference = Math.abs(audioPlayer.currentTime - elapsedTime);

            // 只有当偏差大于 1 秒时才同步
            if (timeDifference > 1) {
                audioPlayer.currentTime = elapsedTime;
            }
        }
    } catch (error) {
        console.error("Error fetching current song:", error);
    }
}

function playNextSong() {
    if (playlist.length > 0) {
        let randomIndex;

        // 确保随机到的不是当前播放的歌曲
        do {
            randomIndex = Math.floor(Math.random() * playlist.length);
        } while (randomIndex === currentSongIndex);
        currentSongIndex = randomIndex;
        console.log("播放下一首: " + playlist[currentSongIndex]);
        playSong(playlist[currentSongIndex]);
    } else {
        console.log("播放列表为空。");
    }
}


// 页面加载时同步当前歌曲并启动定时轮询
window.onload = function () {
    const audioPlayer = document.getElementById("audioPlayer");
    audioPlayer.volume = 0.1;

    // 初始化播放列表
    const songElements = document.querySelectorAll('#playlist li');
    playlist = Array.from(songElements).map(el => el.textContent);

    fetchCurrentSong();               // 页面加载时立即获取播放状态
    setInterval(fetchCurrentSong, 10000); // 每10秒同步一次播放状态
    audioPlayer.addEventListener("ended", playNextSong);
};

// 更新播放歌曲并通知服务器
function playSong(fileName) {
    const audioPlayer = document.getElementById("audioPlayer");
    const songTitle = document.getElementById("songTitle");
    currentSongIndex = playlist.indexOf(fileName);
    // 设置播放的歌曲和标题
    audioPlayer.src = "Music/" + fileName;
    songTitle.innerText = fileName;
    audioPlayer.play();

    // 更新服务器播放状态
    fetch(contextPath + '/listenTogether.MusicControlServlet', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'song=' + encodeURIComponent(fileName)
    }).then(() => {
        // 更新当前状态变量
        currentSong = fileName;
        lastStartTime = Date.now();
    });
}